package com.ft.adbix.utils.permission;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.core.content.ContextCompat;

import com.ft.adbix.utils.data.gather.common.DataGatherManager;

/**
 * @author parting_soul
 * @date 2020-06-09
 */
public class PermissionUtils {

    private PermissionRequestListener mListener;

    private PermissionUtils() {
    }

    private static final class InstanceHolder {
        static final PermissionUtils instance = new PermissionUtils();
    }

    public static PermissionUtils getInstance() {
        return InstanceHolder.instance;
    }

    public static boolean hasPermissions(Context context, boolean isOr, String... permissions) {
        if (permissions == null) {
            return false;
        }
        boolean hasPermission = !isOr;
        for (String permission : permissions) {
            if (isOr) {
                hasPermission |= hasPermission(context, permission);
            } else {
                hasPermission &= hasPermission(context, permission);
            }
        }
        return hasPermission;
    }

    public static boolean hasPermission(Context context, String permssion) {
        return ContextCompat.checkSelfPermission(context, permssion) == PackageManager.PERMISSION_GRANTED;
    }

    public static boolean hasExternalPermission() {
        boolean hasPermission;
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE};
        } else {
            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }
        hasPermission = PermissionUtils.hasPermissions(DataGatherManager.getInstance().getContext(),
                true, permissions);
        return hasPermission;
    }

    public PermissionRequestListener getListener() {
        return mListener;
    }

    public void requestPermission(Context context, PermissionRequestListener listener, String... permissions) {
        mListener = listener;
        if (hasPermissions(context, false, permissions)) {
            listener.onGranted(permissions);
        } else {
            PermissionActivity.requestPermission(context, permissions);
        }
    }

    public interface PermissionRequestListener {
        void onDenied();

        void onGranted(String[] permissions);

    }

}
